<template>
	<div>
		<FormItems
			ref="form"
			v-model="formData"
			:form="formList"
			:state="state"
			labelWidth="100px">
			<template #file>
				<el-button type="text">上传询价依据</el-button>
			</template>
			<template #quantityRequired>
				<el-tooltip
					class="item"
					effect="dark"
					content="当前承租方为个人类型，只能申请一台车辆！"
					placement="top">
					<i class="el-icon-info tip"></i>
				</el-tooltip>
			</template>
		</FormItems>
	</div>
</template>

<script>
	import FormItems from '@/views/finance/manage/formItems/index.vue';
	import FormItem from '@/views/finance/reimburs/formItem/index.vue';
	import { start } from 'nprogress';
	export default {
		components: { FormItems, FormItem },
		props: {
			value: {
				required: false,
			},
			state: {
				required: false,
			},
			type: {
				required: false,
			},
		},
		inject: [
			'details_forecast',
			'_dicts',
			'details_config',
			'deptList',
			'_index',
			'_planDicts',
			'_currentFormData',
		],
		dicts: ['quota_operation_type'],
		data() {
			return {
				typeList: [],
			};
		},
		computed: {
			planDicts() {
				return this._planDicts();
			},
			currentFormData() {
				return this._currentFormData();
			},
			dicts() {
				return this._dicts();
			},
			formData: {
				get() {
					// return this.value;
					return this.useVModel.call(this);
				},
				set(val) {
					this.$emit('input', val);
				},
			},
			config() {
				return this.details_config();
			},
			details() {
				return this.details_forecast();
			},
			index() {
				return this._index();
			},
			formList() {
				return [
					{
						label: '选择车型',
						type: 'select_dialog',
						prop: 'carModelId',
						propLabel: 'carModelName',
						selectDialogParams: {
							type: 'quotaCarType',
							title: '请选择车型',
							params: {
								quotationProductSchemeId:
									this.details?.schemeId,
							},
						},
						rules: true,
						selectDialogValidate: row => {
							if (!this.details?.schemeId) {
								this.$message({
									message: '请选择产品方案',
									type: 'warning',
								});
								return false;
							}
							return true;
						},
						event: {
							type: 'clear',
							cb: row => {
								this.$emitter.emit(
									'initInputState',
									this.currentFormData.sequenceNumber,
								);
								this.$emitter.emit(
									'initCalcData',
									this.currentFormData?.sequenceNumber,
								);
								this.formData.carModelId = undefined; //车型id
								this.formData.carModelName = undefined; //车型
								this.formData.carBrandName = undefined; //品牌
								this.formData.carBrandId = undefined; //品牌id
								this.formData.carSeriesName = undefined; //车系
								this.formData.carSeriesId = undefined; //车系id
								this.formData.carSeating = undefined; // 座位数
								this.formData.carCc = undefined; // 排量
								this.formData.carTypeStr = undefined;
								this.formData.carPowerTypeStr = undefined;
								this.formData.carManufacturer = undefined; // 厂商
								this.formData.carGuidePrice = undefined;
								this.formData.carSeatingType = undefined;
								this.$nextTick(() => {
									this.$emit('getDecorationList');
								});
							},
						},
						cb: res => {
							console.log(res);
							this.$emitter.emit(
								'initInputState',
								this.currentFormData.sequenceNumber,
							);
							this.$emitter.emit(
								'initCalcData',
								this.currentFormData?.sequenceNumber,
							);
							this.formData.carModelId = res.id; //车型id
							this.formData.carModelName = res.modelName; //车型
							this.formData.carBrandName = res.brandName; //品牌
							this.formData.carBrandId = res.carBrandId; //品牌id
							this.formData.carSeriesName = res.seriesName; //车系
							this.formData.carSeriesId = res.carSeriesId; //车系id
							this.formData.carSeatingType = res.seatNumber; // 座位数
							if (/(\-|\/)/g.test(res.seatNumber)) {
								this.formData.carSeating = undefined; // 座位数
							} else {
								this.formData.carSeating = res.seatNumber; // 座位数
							}
							this.formData.carCc = res.liter; // 排量
							this.formData.carTypeStr =
								res.modelType == '1'
									? '乘用车'
									: res.modelType == '2'
									? '物流车'
									: ''; // 车辆种类
							this.formData.isGreen = res.isGreen; // 是否新能源
							// this.formData.carPowerTypeStr = res.fuelTypeName; // 车辆类型
							this.formData.carPowerTypeStr =
								res.isGreen == 1 ? '新能源车' : '燃油车';
							this.formData.carManufacturer = res.makerName; // 厂商
							let price = res.price * 10000;
							this.formData.carGuidePrice = Number.isFinite(price) // 厂商指导价
								? price
								: 0;
							if (res.isGreen == 1) {
								this.$emitter.emit(
									'setInsuranceCarvesselCurrentAmount',
									this.currentFormData.sequenceNumber,
								);
							}
							if (
								this.currentFormData
									?.substituteMaintenanceLevel !== '2' &&
								this.config.businessSource == '2' && //渠道
								this.details.carType == '1' && // 新车
								this.details.carSourceType !== '2' // 不为现有
							) {
								let item = this.planDicts.levelList?.find(e => {
									let startPrice = e?.startMsrp * 10000;
									let endPrice = e?.endMsrp * 10000;
									let startRes = false;
									let endRes = false;
									if (e?.includeStart == 0) {
										startRes = price > startPrice;
									} else if (e?.includeStart == 1) {
										startRes = price >= startPrice;
									} else {
										startRes = true;
									}
									if (e?.includeEnd == 0) {
										endRes = price < endPrice;
									} else if (e?.includeEnd == 1) {
										endRes = price <= endPrice;
									} else {
										endRes = true;
									}
									return startRes && endRes;
								});

								if (
									item &&
									!(
										this.config.businessSource == '1' &&
										this.details.rentType_raw == '2'
									)
								) {
									this.currentFormData.substituteMaintenanceLevel =
										'1';
									this.currentFormData.substituteMaintenanceLevelType =
										item.id;
								}
							}
							this.$emit('getDecorationList');
							console.log(this.formData);
						},
					},
					{
						label: '台数',
						type: 'input_number',
						prop: 'quantityRequired',
						max: this.details.customerTypeCode == 1 ? 1 : Infinity,
						min: 1,
						rules: [
							{
								required: true,
								message: '请输入台数',
							},
							{
								type: 'number',
								min: 1,
								message: '台数最小为 1',
							},
						],
						slot:
							this.details.customerTypeCode == 1
								? 'quantityRequired'
								: '',
					},
					{
						label: '车辆种类',
						prop: 'carTypeStr',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '车辆类型',
						prop: 'carPowerTypeStr',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '品牌',
						prop: 'carBrandName',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '车系',
						prop: 'carSeriesName',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '车辆分类',
						type: 'select',
						selectList: this.typeList,
						selectLabel: 'dictLabel',
						selectValue: 'dictValue',
						prop: 'carSeriesType',
						// show: this.config.businessSource == "1",
						rules:
							this.config.businessSource == '1' &&
							this.details.rentType_raw == '1'
								? true
								: false,
						event: {
							type: 'change',
							cb: row => {
								if (this.notEmpty(row.carSeriesType)) {
									let [key, value] =
										row.carSeriesType?.split('_');
									row.carSeriesTypeKey = key; // 分类
									row.carSeriesTypeVal = value; // 系数
								} else {
									row.carSeriesTypeKey = undefined; // 分类
									row.carSeriesTypeVal = undefined; // 系数
								}
							},
						},
					},
					{
						label: '车型',
						prop: 'carModelName',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '厂商',
						prop: 'carManufacturer',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '座位',
						prop: 'carSeating',
						type: () => {
							if (/(\-|\/)/g.test(this.formData.carSeatingType)) {
								return 'select';
							}
							return 'input_number';
						},
						array: true,
						selectList: row => {
							if (!this.formData?.carSeatingType) {
								return [];
							}
							if (
								this.formData.carSeatingType.indexOf('/') !== -1
							) {
								return this.formData.carSeatingType?.split('/');
							}
							if (
								this.formData.carSeatingType.indexOf('-') !== -1
							) {
								let arr =
									this.formData.carSeatingType?.split('-');
								if (arr?.length < 2) return [];
								let start = arr?.[0] ?? 1;
								let end = arr?.[1];
								let seat = [];
								for (let index = start; index <= end; index++) {
									seat.push(index);
								}
								return seat;
							}
						},
						rules: true,
						state:
							this.type == 'preview'
								? 'readonly'
								: this.showCarSeatSelect
								? 'write'
								: 'disabled',
						event: {
							type: 'change',
							cb: () => {
								this.$emit('getDecorationList');
							},
						},
					},
					{
						label: '排量',
						prop: 'carCc',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '厂商指导价',
						prop: 'carGuidePrice',
						type: 'input_number',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
						tag: 'price',
					},
					{
						label: '车辆使用性质',
						prop: 'operationType',
						type: 'select',
						selectList: this.dict.type.quota_operation_type,
						rules: true,
					},
					{
						label: '外观颜色',
						prop: 'appearanceColor',
						type: 'input',
						rules: [
							{
								required: true,
								message: '请输入外观颜色',
								trigger: 'blur',
							},
						],
					},
					{
						label: '内饰颜色',
						prop: 'interiorColor',
						type: 'input',
						rules: [
							{
								required: true,
								message: '请输入内饰颜色',
								trigger: 'blur',
							},
						],
					},
					// {
					//     label: "过户费",
					//     prop: "transferFee",
					//     type: "input_number",
					//     show: this.details.carType !== "1",
					//     prototype: {
					//         step: 0.01,
					//         stepStrictly: true,
					//     },
					// },
					{
						label: '出库费',
						prop: 'warehouseOutCharge',
						type: 'input_number',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						tag: 'price',
					},
					{
						label: '物流费',
						prop: 'logisticFee',
						type: 'input_number',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						tag: 'price',
					},
					// {
					//     label: "车辆归属",
					//     prop: "carAffiliationKey",
					//     type: "select",
					//     selectList: this.deptList.company,
					//     selectLabel: "deptName",
					//     selectValue: "deptId",
					//     rules: [
					//         {
					//             required: true,
					//             message: "请选择车辆归属城市",
					//             trigger: "change",
					//         },
					//     ],
					//     event: {
					//         type: "change",
					//         cb: (row) => {
					//             let item = this.deptList.company.find(
					//                 (e) => e.deptId == row.carAffiliationKey
					//             );
					//             if (item) {
					//                 this.formData.carAffiliationVal = item.deptName;
					//             }
					//         },
					//     },
					// },
					// {
					//     label: "运营城市",
					//     prop: "carOperateCityKey",
					//     type: "input",
					//     rules: [
					//         {
					//             required: true,
					//             message: "请选择运营城市",
					//             trigger: "change",
					//         },
					//     ],
					// },
					{
						label: '采购价',
						prop: 'purchasePrice',
						type: 'input_number',
						tag: 'price',
						rules: [
							{
								required: true,
								message: '请输入采购价',
								trigger: 'blur',
							},
						],

						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						event: {
							type: 'change',
							cb: () => {
								this.$emitter.emit(
									'initInputState',
									this.currentFormData.sequenceNumber,
								);
								this.$emitter.emit(
									'initCalcData',
									this.currentFormData?.sequenceNumber,
								);
							},
						},
					},
					{
						label: '到期评估价',
						prop: 'finalEvaluationPrice',
						type: 'input_number',
						//  自购 && 旧车 && 自营
						show:
							this.details?.carType == '2' &&
							this.details?.carSourceType == '1' &&
							this.details?.rentType_raw == '1',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						tag: 'price',
						rules: true,
						className: () => {
							return 'finalEvaluationPrice';
						},
						event: {
							type: 'change',
							cb: row => {
								if (this.notEmpty(row.finalEvaluationPrice)) {
									this.currentFormData.planConf.finalEvaluationPrice_state =
										'changed';
								} else {
									this.currentFormData.planConf.finalEvaluationPrice_state =
										'';
								}
							},
						},
					},
					{
						label: 'GPS费用',
						prop: 'gpsFee',
						type: 'input_number',
						rules: true,
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						tag: 'price',
						state:
							this.type == 'preview'
								? 'readonly'
								: this.config?.quotationProductSchemeRule
										?.openGpsModification == 1
								? 'write'
								: 'disabled',
						event: {
							type: 'change',
							cb: row => {
								if (this.notEmpty(row.gpsFee)) {
									this.currentFormData.planConf.gpsFee_state =
										'changed';
								} else {
									this.currentFormData.planConf.gpsFee_state =
										'';
								}
							},
						},
					},
					{
						label: '年检费（年）',
						prop: 'input_number',
						state: 'readonly',
						prop: 'annualCheckFee',
						tag: 'price',
					},
					{
						label: '询价依据',
						prop: 'insuranceConsultAccessory',
						type: 'upload',
						prototype: {
							listType: 'text',
							fileType: ['png', 'jpg', 'jpeg'],
							isShowTip: false,
						},
						uploadEnd: () => {
							this.$refs.form.form_clearValidate(
								'insuranceConsultAccessory',
							);
						},
						formitemPrototype: {
							style: {
								width: '100%',
							},
						},
					},
				];
			},
			showCarSeatSelect() {
				return /(\-|\/)/g.test(this.formData.carSeatingType);
			},
		},
		created() {
			this.getTypeList();
		},
		mounted() {},
		beforeDestroy() {
			if (this.notEmpty(this.details?.productList?.[this.index])) {
				this.$refs.form?.form_resetFields?.();
			}
		},
		methods: {
			getTypeList() {
				this._getDicts('car_classify').then(res => {
					this.typeList = res;
				});
			},
			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (
							Object.prototype.toString.call(ref) ==
							'[object Array]'
						) {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(
										ref,
										'form_validate',
									);
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(
									ref,
									'form_validate',
								);
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.box {
		margin: 20px;
		padding: 20px;
		border-radius: 8px;
		background-color: #fff;
		.title {
			font-size: 16px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			color: #333333;
			line-height: 22px;
			padding-bottom: 15px;
			border-bottom: 1px solid #e9e9e9;
		}
	}
	.tip {
		line-height: 32px;
		margin-left: 5px;
	}
</style>
